﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilZ.Dotnet.Ex.Base;

namespace UtilZ.Dotnet.Ex.Communication.Net.BMQ
{
    /// <summary>
    /// BMQ传话消息接口
    /// </summary>
    public abstract class BMQSessionMessageAbs : BMQMessageAbs, IBMQSessionMessage
    {
        private short _contextId;
        /// <summary>
        /// 上下文会话标识
        /// </summary>
        public short ContextId
        {
            get { return _contextId; }
        }



        /// <summary>
        /// 消息大小,小于0表示变长，变长消息为内容消息
        /// </summary>
        private readonly int _size;

        /// <summary>
        /// 构造函数-解析
        /// </summary>
        /// <param name="messageType">BMQ消息类型</param>
        /// <param name="size">消息大小</param>
        public BMQSessionMessageAbs(byte messageType, int size)
            : base(messageType)
        {
            this._size = size;
        }

        /// <summary>
        /// 构造函数-创建
        /// </summary>
        /// <param name="messageType">BMQ消息类型</param>
        /// <param name="size">消息大小</param>
        /// <param name="contextId">上下文会话标识</param>
        public BMQSessionMessageAbs(byte messageType, int size, short contextId)
            : base(messageType)
        {
            this._size = size;
            this._contextId = contextId;
        }


        /// <summary>
        /// 获取消息大小
        /// </summary>
        /// <returns>消息大小</returns>
        protected override int GetMessageSize()
        {
            return this._size;
        }

        /// <summary>
        /// 将消息写入二进制buffer
        /// </summary>
        /// <param name="writer">消息写器</param>
        protected override void WriteMessage(BinaryWriter writer)
        {
            writer.Write(this._messageType);
            writer.Write(this._contextId);
            this.WriteBytes(writer);
        }


        /// <summary>
        /// 将消息写入二进制buffer
        /// </summary>
        /// <param name="writer">消息写器</param>
        protected abstract void WriteBytes(BinaryWriter writer);


        /// <summary>
        /// 读取消息到对象
        /// </summary>
        /// <param name="reader">消息读取器</param>
        protected override void ReadMessage(BinaryReader reader)
        {
            byte messageType = reader.ReadByte();
            this._contextId = reader.ReadInt16();
            this.PrimitiveFromBytes(reader);
        }

        /// <summary>
        /// 读取消息到对象
        /// </summary>
        /// <param name="reader">消息读取器</param>
        protected abstract void PrimitiveFromBytes(BinaryReader reader);


    }
}
